package com.baidu.test;

import com.baidu.pojo.User;
import com.baidu.utils.HibernateUtils;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Restrictions;
import org.hibernate.query.Query;
import org.junit.Test;

import java.util.List;

public class HibernateTest02 {

    /*
    * 使用Query的方式
    * */
    @Test
    public void test01(){
        SessionFactory sessionFactory = HibernateUtils.getSessionFactory();
        Session session = sessionFactory.openSession();

        // 查询所有数据
        Query queryList = session.createQuery("from User");
        List<User> list = queryList.list();
        for (User user : list) {
            System.out.println(user);
        }

        // 根据条件查询
        Query queryWhere = session.createQuery("from User where userName = ?");
        queryWhere.setString(0,"1344433");
        List<User> list1 = queryWhere.list();
        System.out.println(list1);

        // 根据条件查询
        Query queryWhereAnd = session.createQuery("from User where userName = :aa and password = :bb");
        queryWhereAnd.setString("aa","vc");
        queryWhereAnd.setString("bb","fff");
        List<User> list2 = queryWhereAnd.list();
        System.out.println(list2);

        Query queryWhereAnd2 = session.createQuery("from User where userName = ? and password = ?");
        queryWhereAnd2.setString(0,"vc");
        queryWhereAnd2.setString(1,"fff");
        List<User> list3 = queryWhereAnd2.list();
        System.out.println(list3);


    }

    /*
    * Criteria方式查询
    * */
    @Test
    public void test02(){
        SessionFactory sessionFactory = HibernateUtils.getSessionFactory();
        Session session = sessionFactory.openSession();

        // 查询所有
        Criteria criteriaList = session.createCriteria(User.class);
        List<User> list = criteriaList.list();
        System.out.println(list);

        // 条件查询
        Criteria criteriaWhere = session.createCriteria(User.class);
        criteriaWhere.add(Restrictions.eq("userName","123"));
        List<User> list1 = criteriaWhere.list();
        System.out.println(list1);

        // 多条件查询
        Criteria criteriaWhereAnd = session.createCriteria(User.class);
        criteriaWhereAnd.add(Restrictions.eq("userName","123"));
        criteriaWhereAnd.add(Restrictions.eq("password","345"));
        List<User> list2 = criteriaWhereAnd.list();
        System.out.println(list2);
    }

    /*
    * SQLQuery查询
    * */


}
